package com.etheart.framework.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Browser {
	public static String REQUEST_ATTR_NAME="com_etheart_browser";
	private List<String> scripts;
	public static void exeAlter(Map<String, Object> request,String message){
		Browser browser = getBrowser(request);
		browser.add("alert(\""+message+"\");\r\n");
	}
	public static void exeJavascriptMethod(Map<String, Object> request,String method,String ...params){
		Browser browser = getBrowser(request);
		StringBuffer buffer = new StringBuffer(method+"(");
		for (int i = 0; i < params.length; i++) {
			if (i!=0) {
				buffer.append(",");
			}
			buffer.append(params[i]);
		}
		buffer.append(");\r\n");
		browser.add(buffer.toString());
	}
	
	public static void exeJavascriptMethod(Map<String, Object> request,String method){
		Browser browser = getBrowser(request);
		browser.add(method+";\r\n");
	}

	private static Browser getBrowser(Map<String, Object> request) {
		Browser browser = (Browser) request.get(REQUEST_ATTR_NAME);
		if (browser == null) {
			browser = new Browser();
			request.put(REQUEST_ATTR_NAME, browser);
		}
		return browser;
	}
	public void add(String script) {
		if (scripts ==null) {
			scripts = new ArrayList<String>();
		}
		scripts.add(script);
	}
	public List<String> getScripts() {
		return scripts;
	}
	public void setScripts(List<String> scripts) {
		this.scripts = scripts;
	}
	
	public static void writeScript(HttpServletRequest request,HttpServletResponse response) throws IOException {
		Browser browser = (Browser) request.getAttribute(Browser.REQUEST_ATTR_NAME);
		if (browser != null ) {
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.println("<script type=\"text/javascript\"><!--");
			for (String script : browser.getScripts()) {
				out.println(script);
			}
			out.println("//--></script>");
			out.flush();
			Browser.removeScript(request);
		}
	}
	@SuppressWarnings("unused")
	private static void removeScript(Map<String, Object> request) {
		request.remove(REQUEST_ATTR_NAME);
	}
	
	private static void removeScript(HttpServletRequest request) {
		request.removeAttribute(REQUEST_ATTR_NAME);
	}
}	
